from beanie import Document
from beanie.operators import Inc
from pymongo import ReturnDocument
from core.logger import log

class SequenceCounter(Document):
    name: str
    value: int = 0

    @classmethod
    async def get_next_sequence(cls, name: str) -> int:
        """
        获取下一个序列号（原子操作）
        :param name: 序列名称（session_id）
        :return: 下一个序列号
        """
        # 查找现有记录
        try:
            counter = await cls.find_one(cls.name == name)
        except Exception as e:
            # 根据实际日志系统记录异常信息
            log.exception(e)


        if counter:
            # 存在则递增
            await counter.update({"$inc": {"value": 1}})
            return counter.value
        else:
            # 不存在则创建新记录并返回 1
            new_counter = SequenceCounter(name=name, value=1)
            await new_counter.insert()
            return 1